package bg.openid.joid;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.verisign.joid.AssociationRequest;
import org.verisign.joid.AssociationResponse;
import org.verisign.joid.AuthenticationRequest;
import org.verisign.joid.Crypto;
import org.verisign.joid.DiffieHellman;
import org.verisign.joid.OpenIdException;
import org.verisign.joid.Response;
import org.verisign.joid.SimpleRegistration;
import org.verisign.joid.consumer.Util;

// bg.openid.joid.ServletOpenidJoid 
public class ServletOpenidJoid extends HttpServlet {

	public ServletOpenidJoid() {
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Bean bean = getBean(request);
		bean.addComment("GET!!!!!!");
		bean.display(request);
		// UtilAssociate.getInstance().verivy()
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/bg.jsp");
		dispatcher.forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Bean bean = getBean(request);
		String action = request.getParameter("action");
		String identifier = request.getParameter("identifier");
		bean.addComment("action", action);
		bean.addComment("identifier", identifier);
		try {
			if (action == null) {
			} else if (action.equals("clean")) {
				bean.clean();
			} else if (action.equals("associate")) {
				this.associate(request, response, bean);
			} else if (action.equals("authenticate")) {
				this.authenticate(request, response, bean);
				return;
			} else if (action.equals("login")) {

			}
		} catch (Exception e) {

			e.printStackTrace();
			bean.addException(e);
		}
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/bg.jsp");
		dispatcher.forward(request, response);
	}

	private void associate(HttpServletRequest request, HttpServletResponse response, Bean bean) throws Exception {
		bean.setComment("associate !!! ");
		String identity = request.getParameter("identifier");
		
		bean.display(UtilAssociate.getInstance().getPSecret(identity));
	}

	private void authenticate(HttpServletRequest request, HttpServletResponse response, Bean bean) throws Exception {
		bean.setComment("authenticate  ");
		String identity = request.getParameter("identifier");
		String returnTo = "http://www.java-consultant.com/joid/openidJoid";
		String trustRoot = "http://www.java-consultant.com/";
		Properties p = UtilAssociate.getInstance().getPSecret(identity);
		// UtilAuthenticate.getInstance().authenticate(identity, returnTo,
		// trustRoot, p,bean, request);
		String handle = p.getProperty("handle");
		String dest = p.getProperty("_dest");

		AuthenticationRequest ar = AuthenticationRequest.create(identity, returnTo, trustRoot, handle);
		
		ar.getSimpleRegistration().setRequired(SimpleRegistration.allowed);
		ar.getSimpleRegistration().getSuppliedValues();
		//ar.getSimpleRegistration().setOptional(SimpleRegistration.allowed);
		bean.addComment("Authenticate: dest:", dest);
		bean.addComment("Authenticate: sreg:", ar.getSimpleRegistration());
		bean.addComment("Authenticate: ar: ", ar);
		bean.addComment("Authenticate: ar.toURL: ", ar.toUrlString());
		//String fullUrl = dest + "?" + ar.toUrlString() + "&" + this.getAx();
		//String fullUrl = dest + "?" + ar.toUrlString() ;
		//String fullUrl = dest + "?" + ar.toUrlString() +"&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.required=fullname,email&openid.sreg.optional=gender,nickname";
		String fullUrl = dest + "?" + ar.toUrlString() +getSreg();
		bean.displayUrl(fullUrl);
		bean.addComment("Authenticate: ar.fullURL: ", "<a href='" + fullUrl + "'>test</a>");
		response.sendRedirect(fullUrl);
	}

	//openid.sreg.optional=email
	//"&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.required=fullname,email&openid.sreg.optional=gender,nickname";
	private String getSreg() {
		String r = "";
		r += getEncoded("openid.ns.sreg", "http://openid.net/extensions/sreg/1.1");
		r += getEncoded("openid.sreg.required", "fullname,email");
		r += getEncoded("openid.sreg.optional", "gender,nickname");
		return r;
	}
	private String getAx__OLD_DOESNT8WORK() {
		String r = "";
		r += getEncoded("openid.ns.ax", "http://openid.net/srv/ax/1.0");
		r += getEncoded("openid.ax.mode", "fetch_request");
		//r += getEncoded("openid.ax.required", "name,hackergotchi");
		r += getEncoded("openid.ax.if_available", "email,web,name,hackergotchi");
		r += getEncoded("openid.ax.type.name", "http://axschema.org/namePerson");
		r += getEncoded("openid.ax.type.email", "http://axschema.org/contact/email");
		r += getEncoded("openid.ax.type.hackergotchi", "http://axschema.org/media/image/default");
		r += getEncoded("openid.ax.type.web", "http://axschema.org/contact/web/default");
		return r;
	}

	private String getEncoded(String k, String v) {
		return "&"+k.trim() + "=" + URLEncoder.encode(v);
	}

	private Bean getBean(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		Bean b = (Bean) session.getAttribute("bean");
		if (b == null) {
			b = new Bean();
		}
		return b;
	}

}
